import pymysql

from app.util.log_util import log


def get_db():
    try:
        _db = pymysql.connect("localhost", "root", "HHup7856_@pp", "tianmu", charset="utf8")
    except Exception as e:
        log(e.__str__())
        try:
            _db = pymysql.connect("rm-2ze488repumd0716l.mysql.rds.aliyuncs.com", "tianmu_read", "Woshijidutu2018",
                                  "tianmu", charset="utf8")
        except Exception as e:
            log(e.__str__())
            return None
    log('database is ok')
    return _db


db = None
cursor = None


def init_db():
    global db, cursor

    if db and db.open:
        # 使用 cursor() 方法创建一个游标对象 cursor
        cursor = db.cursor()

        # 使用 execute()  方法执行 SQL 查询
        cursor.execute("SELECT VERSION()")

        # 使用 fetchone() 方法获取单条数据.
        data = cursor.fetchone()

        log("Database version : %s " % data)
        return

    db = get_db()
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()

    # 使用 execute()  方法执行 SQL 查询
    cursor.execute("SELECT VERSION()")

    # 使用 fetchone() 方法获取单条数据.
    data = cursor.fetchone()
    log("Database version : %s " % data)


def close_db():
    global db
    if db:
        db.close
        log('Database is closed.')


def test():
    init_db()
    sql = 'select * from brand'
    try:
        # 执行SQL语句
        cursor.execute(sql)
        # 获取所有记录列表
        results = cursor.fetchall()
        for row in results:
            print(row[0], row[1])
    except:
        print("Error: unable to fetch data")
    close_db()

